// pages/goods_detail/index.js
import regeneratorRuntime from '../../lib/runtime/runtime';
import {
  request
} from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj: {

    },
    isCollect:false
  },
  // 商品对象
  GoodsInfo: {},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const {
      goods_id
    } = options
    this.getGoodsDetail(goods_id)
  },

  // 获取商品详情数据
  async getGoodsDetail(goods_id) {
    const goodsObj = await request({
      url: "/goods/detail",
      data: {
        goods_id
      }
    });
    this.GoodsInfo = goodsObj
    let collect = wx.getStorageSync('collect') || []
    let isCollect = collect.some(e=>e.goods_id==this.GoodsInfo.goods_id)
    this.setData({
      goodsObj: {
        goods_name: goodsObj.goods_name,
        goods_price: goodsObj.goods_price,
        // iphone部分手机 不识别 webp图片格式 
        // 最好找到后台 让他进行修改 
        // 临时自己改 确保后台存在 1.webp => 1.jpg 
        goods_introduce: goodsObj.goods_introduce.replace(/\.webp/g, '.jpg'),
        pics: goodsObj.pics
      },
      isCollect
    })
  },
  // 点击轮播图预览大图
  handlePrevewImage(e) {
    console.log(e);
    const current = e.currentTarget.dataset.url
    const urls = this.data.goodsObj.pics.map(e => e.pics_mid)

    wx.previewImage({
      current,
      urls
    })
  },

  handleCartAdd() {
    // 1 获取缓存中的购物车 数组
    //到这样的元素，findIndex会立即返回该元素的索引,则findIndex返回-1
    const cart = wx.getStorageSync('cart') || []
    // 2 判断 商品对象是否存在于购物车数组中
    const index = cart.findIndex(e => e.goods_id === this.GoodsInfo.goods_id)
    console.log(index);
    if (index === -1) {
      //3  不存在 第一次添加
      this.GoodsInfo.checked = true;
      this.GoodsInfo.num = 1
      cart.push(this.GoodsInfo)
    } else {
      cart[index].num++
    }
    wx.setStorageSync('cart', cart)

    wx.showToast({
      title: '加入成功',
      icon: 'success',
      // true 防止用户 手抖 疯狂点击按钮 
      mask: true
    });
  },
  handleCollect(){
    let isCollect = false
    let collect = wx.getStorageSync('collect') || []
    let index = collect.findIndex(v=>v.goods_id==this.GoodsInfo.goods_id)
    if(index !== -1){
      // 能找到 已经收藏过了  在数组中删除该商品
      collect.splice(index,1)
      isCollect = false
      wx.showToast({
        title: '取消成功',
        icon: 'success',
        mask: true
      });
    }else{
      //没有收藏
      collect.push(this.GoodsInfo);
      isCollect = true
    }
     // 4 把数组存入到缓存中
     wx.setStorageSync("collect", collect);
     // 5 修改data中的属性  isCollect
     this.setData({
       isCollect
     })
  }
})